<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>History 模式</title>
  </head>
  <body>
    <div>
    	<ul>
            <li><a href="#/page1">page1</a></li>
            <li><a href="#/page2">page2</a></li>
        </ul>
        <div id="route-view"></div>
    </div>
    <script type="text/javascript">
    	//下面为 History 的路由实现方式
        window.addEventListener('DOMContentLoaded', Load)
        window.addEventListener('popstate', PopChange)
        var routeView = null
        function Load() {
            routeView = document.getElementById('route-view')
            //默认执行一次
            PopChange()
            //获取所有带href属性的a标签节点
            var aList = document.querySelectorAll('a[href]')
            //遍历a标签节点数组，阻止默认事件，添加单击事件回调函数
            aList.forEach(aNode => aNode.addEventListener('click', function(e){
                e.preventDefault() //阻止a标签的默认事件
                var href = aNode.getAttribute('href')
                //手动修改浏览器的地址栏
                history.pushState(null, '', href)
                //通过history.pushState手动修改地址栏
                //popstate监听不到地址栏的变化，所以此处需要手动执行回调函数PopChange()
                PopChange()
            }))
        }
        function PopChange() {
            console.log('location', location)
            //给route-view赋值
            switch(location.hash){
                case '#/page1':
                    routeView.innerHTML = 'page1'
                    return
                case '#/page2':
                    routeView.innerHTML = 'page2'
                    return 
                default:
                    routeView.innerHTML = 'page1'
                    return
            }
        }
    </script>
  </body>
</html>
